package com.xjmall.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by An on 2017/8/21.
 */
@ControllerAdvice
public class ExceptionHandlingConfiguration {

    /**
     * 不知如何处理的异常统一向这里抛出
     * @param request
     * @param e
     * @return
     * @throws Exception
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    public Error defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
        return buildErrorResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    /**
     * 数据找不到异常
     * @param request
     * @param e
     * @return
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(value = DataNotFoundException.class)
    public Error dataNotFoundException(HttpServletRequest request, DataNotFoundException e) throws Exception {
        return buildErrorResult(HttpStatus.NOT_FOUND.value(), e.getMessage());
    }

    /**
     * 构建错误信息
     * @param code
     * @param message
     * @return
     */
    private Error buildErrorResult(int code, String message) {
        return new Error(code, message);
    }
}
